package com.jwell.panrank.retrofit

import android.content.Context
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.jwell.driverapp.retrofit.ApiStore
import com.jwell.driverapp.tools.Utils
import com.jwell.panrank.application.App
import com.jwell.panrank.tools.DataModel
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Created by Administrator on 2017/10/11.
 */
class RetrofitFactory private constructor() {
    companion object {
        val instance = RetrofitFactory()
//        val BASE_URL = "http://221.237.162.142:11084/"//外网攀钢排位系统
        val BASE_URL = "http://221.237.162.142:15001/"//内网攀钢排位系统
//        val BASE_URL = "https://phxt.jwell56.com/"//正式环境
        val TIME_OUT: Long = 10
    }

    /**
     * 请求头必须添加的一个KEY，用于确定用户是否别处登录
     */
    private val URL_ADDRESS_HEARD_KEY = "Authorization"
    /**
     * 请求头必须添加的一个KEY对应的VALUE值，用于确定用户是否别处登录
     */
    private val URL_ADDRESS_HEARD_VALUE = "Bearer "

    private var retrofit: Retrofit? = null
    private var apiStore: ApiStore? = null

    init {
        if (retrofit == null) createRetrofit(App.instance)
    }


    /**
     * 配置OkHttpClient、Retrofit、ApiStore三个关键对象
     * @param context
     */
    private fun createRetrofit(context: Context) {
        retrofit = Retrofit.Builder()
                .client(constructClient(context))
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        apiStore = retrofit?.create(ApiStore::class.java)
    }

    /**
     * 创建OkHttp
     */
    private fun constructClient(context: Context): OkHttpClient? {
        val cacheSize: Long = 10 * 1024 * 1024
        val file = context.externalCacheDir
        //添加请求头
        val requestInterceptor = Interceptor { chain ->
            val request = chain.request()
            val key = DataModel.getInstance().token
            val compressedRequest: Request
            val builder = request.newBuilder()
            builder.header("Accept-Language", Locale.getDefault().toString())
            builder.header("Accept-Charset", "UTF-8")
            builder.header("Connection", "Keep-Alive")
            if (App.DEBUG) println("Token" + key)
            if (key != null && !key.isEmpty()) {
                builder.header(URL_ADDRESS_HEARD_KEY, URL_ADDRESS_HEARD_VALUE + key)
            }
            compressedRequest = builder.build()
            chain.proceed(compressedRequest)
        }
        var builder = OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT + 10, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT + 10, TimeUnit.SECONDS)
                .addInterceptor(LoggingInterceptor())
                .addInterceptor(requestInterceptor)
                .cache(Cache(file, cacheSize))
                .retryOnConnectionFailure(true)

        builder.addNetworkInterceptor(getNetworkInterceptor())
                .addInterceptor(getInterceptor())

        var client = builder.build()

        return client
    }

    private fun LoggingInterceptor(): Interceptor? {
        return HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { print(it) })
                .setLevel(HttpLoggingInterceptor.Level.BODY)
    }


    private fun getNetworkInterceptor(): Interceptor? {
        return Interceptor { chain ->
            val request = chain.request()
            val response = chain.proceed(request)
            if (Utils.isNetworkAvailable()) {
                val maxAge = 0
                // 有网络时 设置缓存超时时间0个小时
                response.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .build()
            } else {
                // 无网络时，设置超时为1天
                val maxStale: Long = 60 * 60 * 24 * 1
                response.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build()
            }
            response
        }
    }

    /**
     * 设置返回数据的  Interceptor  判断网络   没网读取缓存
     */
    private fun getInterceptor(): Interceptor {
        return Interceptor { chain ->
            var request = chain.request()
            if (!Utils.isNetworkAvailable()) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build()
            }
            chain.proceed(request)
        }
    }

    /**
     * 将构造好的service对象返回出去

     * @return NetService
     */
    fun getService(): ApiStore = apiStore!!
}